package com.hitqz.robot.daemon.quartz.service.impl;

import cn.hutool.core.util.HexUtil;
import com.hitqz.robot.daemon.quartz.service.TriColourLightService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class TriColourLightServiceImpl implements TriColourLightService {

    /**
     * 目前所有三色灯ip都是192.168.1.232，暂时写死
     */
    private static final String HOST = "192.168.1.232";
    private static final int PORT = 10000;

    private static final Map<String, byte[]> COMMANDS = new HashMap<>();

    static {
        COMMANDS.put("red_on", HexUtil.decodeHex("FE 05 00 00 FF 00 98 35"));
        COMMANDS.put("red_off", HexUtil.decodeHex("FE 05 00 00 00 00 D9 C5"));
        COMMANDS.put("yellow_on", HexUtil.decodeHex("FE 05 00 01 FF 00 C9 F5"));
        COMMANDS.put("yellow_off", HexUtil.decodeHex("FE 05 00 01 00 00 88 05"));
        COMMANDS.put("green_on", HexUtil.decodeHex("FE 05 00 02 FF 00 39 F5"));
        COMMANDS.put("green_off", HexUtil.decodeHex("FE 05 00 02 00 00 78 05"));
        COMMANDS.put("buzzer_on", HexUtil.decodeHex("FE 05 00 03 FF 00 68 35"));
        COMMANDS.put("buzzer_off", HexUtil.decodeHex("FE 05 00 03 00 00 29 C5"));
    }

    /**
     * 初始化
     * 系统亮绿灯
     */
    @PostConstruct
    @Override
    public void init() {
        this.greenLightOn();
        this.redLightOff();
        this.buzzerOff();
    }

    /**
     * 红灯开
     */
    @Override
    public void redLightOn() {
        CompletableFuture.runAsync(()->  {
            try {
                this.sendCommand("red_on");
            } catch (Exception e) {
                log.error("[三色灯]：通信失败", e);
            }
        });
    }

    /**
     * 红灯关
     */
    @Override
    public void redLightOff() {
        CompletableFuture.runAsync(()->  {
            try {
                this.sendCommand("red_off");
            } catch (Exception e) {
                log.error("[三色灯]：通信失败", e);
            }
        });
    }

    /**
     * 黄灯开
     */
    @Override
    public void yellowLightOn() {
        try {
            this.sendCommand("yellow_on");
        } catch (Exception e) {
            log.error("[三色灯]：通信失败", e);
        }
    }

    /**
     * 黄灯关
     */
    @Override
    public void yellowLightOff() {
        try {
            this.sendCommand("yellow_off");
        } catch (Exception e) {
            log.error("[三色灯]：通信失败", e);
        }
    }

    /**
     * 绿灯开
     */
    @Override
    public void greenLightOn() {
        CompletableFuture.runAsync(()->  {
            try {
                this.sendCommand("green_on");
            } catch (Exception e) {
                log.error("[三色灯]：通信失败", e);
            }
        });

    }

    /**
     * 绿灯关
     */
    @Override
    public void greenLightOff() {
        CompletableFuture.runAsync(()->  {
            try {
                this.sendCommand("green_off");
            } catch (Exception e) {
                log.error("[三色灯]：通信失败", e);
            }
        });
    }

    /**
     * 蜂鸣开
     */
    @Override
    public void buzzerOn() {
        CompletableFuture.runAsync(()->  {
            try {
                this.sendCommand("buzzer_on");
            } catch (Exception e) {
                log.error("[三色灯]：通信失败", e);
            }
        });
    }

    /**
     * 蜂鸣关
     */
    @Override
    public void buzzerOff() {
        CompletableFuture.runAsync(()->  {
            try {
                this.sendCommand("buzzer_off");
            } catch (Exception e) {
                log.error("[三色灯]：通信失败", e);
            }
        });
    }

    public void sendCommand(String commandKey) throws InterruptedException {
        byte[] command = COMMANDS.get(commandKey);
        if (command == null) {
            log.error("[三色灯]：Invalid command key: {}", commandKey);
            return;
        }
        try {
            Socket socket = new Socket(HOST, PORT);
            socket.setSoTimeout(60000);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.write(command);
            out.close();
            socket.close();
        } catch (Exception e) {

        }
        //EventLoopGroup group = new NioEventLoopGroup();

        //try {
        //    Bootstrap b = new Bootstrap();
        //    b.group(group)
        //            .channel(NioSocketChannel.class)
        //            .handler(new ChannelInitializer<SocketChannel>() {
        //                @Override
        //                public void initChannel(SocketChannel ch) throws Exception {
        //                    ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
        //                        @Override
        //                        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        //                            // 处理响应
        //                            byte[] response = new byte[msg.readableBytes()];
        //                            msg.readBytes(response);
        //                            log.info("[三色灯]：Received response: {}", HexUtil.encodeHexStr(response));
        //                        }
        //
        //                        @Override
        //                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //                            log.error("[三色灯]：通信失败", cause);
        //                            ctx.close();
        //                        }
        //                    });
        //                }
        //            });
        //
        //    ChannelFuture f = b.connect(HOST, PORT).sync();
        //    ByteBuf buffer = Unpooled.buffer(command.length);
        //    buffer.writeBytes(command);
        //    f.channel().writeAndFlush(buffer);
        //
        //    f.channel().closeFuture().sync();
        //} finally {
        //    group.shutdownGracefully();
        //}
    }
}
